import { Request, Response, NextFunction } from 'express'
import { check, body, validationResult } from 'express-validator'

import { User, UserDocument } from '../models/User'

export const getLogin = (req: Request, res: Response) => {
  if (Reflect.has(req, 'user')) {
    res.redirect('/')
  }

  res.render('account/login', {
    title: 'login'
  })
}

export const getSignup = (req: Request, res: Response) => {
  if (Reflect.has(req, 'user')) {
    res.redirect('/')
  }

  res.render('account/signup', {
    title: 'Create Account'
  })
}

export const postSignup = async (req: Request, res: Response, next: NextFunction) => {
  console.log('请求', req.body)
  await check('email', 'valid email').isEmail().run(req)
  await check('password', '密码至少为4位数').isLength({ min: 4 }).run(req)
  await check('confirmPassword', '密码至少为4位数').equals(req.body.password).run(req)
  await body('emial').normalizeEmail({ gmail_remove_dots: false }).run(req)

  const errors = validationResult(req)
  if (!errors.isEmpty()) {
    console.log(errors.array())
    req.flash("errors", errors.array().map(error => error.msg))
    return res.redirect('/signup')
  }

  const user = new User({
    email: req.body.email,
    password: req.body.password
  })

  User.findOne({
    emial: req.body.email
  },
    (err: NativeError, existingUser: UserDocument) => {
      if (err)
        return next(err)

      if (existingUser) {
        req.flash("errors", '账号已存在')
        return res.redirect("/signup")
      }

      user.save((err) => {
        if (err) {
          return next(err)
        }
        req.logIn(user, (err) => {
          if (err) {
            return next(err)
          }
          res.redirect('/')
        })
      })
    })
}